<?php

if(!defined('IN_SYS')) exit('Access Denied');

class admin_controller extends admincp{

	public function __construct(){
		parent::__construct();
	}

	public function index(){
		$pg = new page("select * from `admin` where id!=1 order by id asc");
		$list = $pg->get_list(15);
		$page = $pg->get_page();
		require self::tpl("admin");
	}

	public function add(){
		if(IS_POST){
			$r = gp("username,password,password2");
			if(db::find("select * from admin where username='$r[username]'  ")){
				exit("用户已存在");
			}
			if(empty($r['password'])){
				exit("请输入密码");
			}
			if($r['password']!=$r['password2']){
				exit("两次输入的密码不一致");
			}
			$rand = rand(1000,9999);
			$password = admin::password_encode($r['username'], $r['password'], $rand);
			db::query("insert into admin (username, password, salt) values ('$r[username]', '$password', $rand) ");
			self::json( array('status' => 1, 'msg' => '添加成功', 'redirect' => '?m=admin') );
		}else{
			require self::tpl("admin_add");
		}
	}

	public function del(){
		$id = intval(gp('id'));
		db::query("delete from admin where where id!=1 and id={$id}");
		self::redirect("?m=admin", "删除成功");
	}

	public function password(){
		if(IS_POST){
			$uid = $this->user['id'];
			$oldpwd = gp('oldpwd');
			$password = gp('password');
			$password2 = gp('password2');
			$old = db::find("select * from admin where id='$uid' ");
			if(admin::password_encode($this->user['username'], $oldpwd, $old['salt']) != $old['password'] ){
				exit("原密码输入有误");
			}
			if(empty($password)){
				exit("请输入新密码");
			}
			if($password!=$password2){
				exit("两次输入的密码不一致");
			}
			$rand = rand(1000,9999);
			$password = admin::password_encode($this->user['username'], $password, $rand);
			db::query("update admin set password='$password',salt='$rand' where id= '$uid' ");
			self::json( array('status' => 1, 'msg' => '修改成功', 'redirect' => '?m=admin') );
			exit("success");
		}else{
			require self::tpl("admin_password");
		}
	}


}
